<?php
namespace lightblog\admin\model;

use lightblog\engine\activeRecord;

class articleModel extends activeRecord {

    public $title;
    public $content;
    public $category;
    public $author;
    public $tags;
    public $aid;

    /**
     * 向数据库新加文章
     */
    function addNewArticle() {
        // 我不想文章也被htmlspecialchars弄得一团糟
        // 所以在存入数据库时, 给decode, 显示时在重新编码
        $content = htmlspecialchars_decode($this->content);
        $author = $this->author ? : 'Sidgwick';
        $time = time();
        $display = 1;

        // 如果没有在标题栏写标题, 就截取正文的标题
        $this->title = $this->title ? : $this->mkHeader($this->content);
        $title = $this->title;

        $sql_field = "(`title`, `content`, `time`, `author`, `display`)";
        $sql_value = "('{$title}', '{$content}', from_unixtime($time), '{$author}', $display)";
        $sql = "INSERT INTO `article` $sql_field VALUES $sql_value";
        $this->aid = $this->insert($sql);

        $this->setArticleCategory(array(1, 2, 3), $this->aid);
        $this->setArticleTags(array(1, 2), $this->aid);

        return $this->aid;
    }

    /**
     * 截取Markdown文章的标题
     * @param string $md Markdown文章
     *
     * @return string 找到的标题
     */
    function mkHeader($md) {
        $md = trim($md);

        $arr = explode("\n", $md);

        if (count($arr) <= 1) {
            $md = trim($md, "# \n\t");
            return substr($md, 0, 8);
        }

        $res = preg_match('/^[=]{3,}/', trim($arr[1]));
        if ($res) {
            return $arr[0];
        } else {
            return trim($arr[0], "# \n\t");
        }

    }

    /**
     * 把文章的分类属性记录到数据库里面去
     */
    function setArticleCategory(array $category, $aid = "") {
        $sql = "INSERT INTO `article_category` (`article`, `category`) VALUES ";
        foreach ($category as $v) {
            $sql .= "({$this->aid}, $v), ";
        }

        $sql = substr($sql, 0, -2);

        return $this->insert($sql);
    }

    /**
     * 把文章的标签属性记录到数据库里面去
     */
    function setArticleTags(array $tags, $aid = "") {
        $sql = "INSERT INTO `article_tags` (`article`, `tags`) VALUES ";
        foreach ($tags as $v) {
            $sql .= "({$this->aid}, $v), ";
        }

        $sql = substr($sql, 0, -2);

        return $this->insert($sql);
    }

    /**
     * 获得所有的category
     */
    function getCategory() {
        $sql = "SELECT * FROM `category`";

        return $this->select($sql, true);
    }

    /**
     * 获得所有的tags
     */
    function getTags() {
        $sql = "SELECT * FROM `tags`";

        return $this->select($sql, true);
    }
}
